var crypto=require("crypto");
var token={
    createToken:function(obj,timeout){  // 生成token
        // Headers
        var obj1 = {
            "alg": "HS256",
            "typ": "JWT"
        }
        var headers = Buffer.from(JSON.stringify(obj1), "utf8").toString("base64");

        console.log(parseInt(timeout)||0);
        var obj2={
            data:obj,//payload
            created:parseInt(Date.now()/1000),//token生成的时间的，单位秒
            exp:parseInt(timeout)||600//token有效期
        };


        //payload信息
        var base64Str=Buffer.from(JSON.stringify(obj2),"utf8").toString("base64");

        //添加签名，防篡改
        var secret="test";
        var hash=crypto.createHmac('sha256',secret);
            hash.update(headers);
            hash.update(base64Str);
        var signature=hash.digest('base64');


        return headers + "." + base64Str + "." + signature;
    },
    decodeToken:function(token){

        var decArr=token.split(".");
        console.log(decArr, decArr.length)
        if(decArr.length<3){
            //token不合法
            return false;
        }

        var payload = {};

        //将payload json字符串 解析为对象
        try{
            payload=JSON.parse(Buffer.from(decArr[1],"base64").toString("utf8"));
        }catch(e){
            return false;
        }

        //检验签名
        var secret="test";        
        var hash=crypto.createHmac('sha256',secret);
            hash.update(decArr[0]);
            hash.update(decArr[1]);
        var checkSignature=hash.digest('base64');

        return {
            payload:payload,
            signature:decArr[2],
            checkSignature:checkSignature
        }
    },
    checkToken:function(token){  // 验证token
        var resDecode=this.decodeToken(token);
        console.log(resDecode)
        if(!resDecode){

            return false;
        }

        //是否过期
        var expState=(parseInt(Date.now()/1000)-parseInt(resDecode.payload.created))>parseInt(resDecode.payload.exp)?false:true;
        if (resDecode.signature === resDecode.checkSignature && expState) {

            return true;
        }

        return false;
    }
    
}

module.exports = token

// var k = token.createToken({name:'admin',possword:'asddfg'}, 5)

// console.log(k)

// var is = token.checkToken(k)
// console.log(is)

// setTimeout(()=>{
//     is = token.checkToken(k)
//     console.log(is)
// }, 6000)